import mongoose from 'mongoose'
//mongoose.connect("mongodb://admin:1234qwer@ds133328.mlab.com:33328/wise")
//mongoose.connect("mongodb://120.24.240.193/wise")
mongoose.connect("mongodb://localhost/wise")
import crypto from 'crypto'
import fs from 'fs'
import utility from 'utility'
import gravatar from 'gravatar'
import {Comment, Dataset, User} from '../models';
import {admin, user1, user2, user3, user4, comment1} from './users';

const clearCollection = async (model) => { await model.remove({}); }

const generatePwd = (pwd) =>  crypto.createHash('sha256').update(pwd).digest('base64').toString();

const saveUser = async (user) => {
  user.password = user.name === 'admin' ? generatePwd("adminwise") : generatePwd("1234qwer");
  user.hashId = utility.md5(user.email);
  return await user.save();
}

const saveDataset = async (dataset) => {
  const [metas, content] = dataset.split('--------\n');
  const [title,url,description,scene,month,freq,sendnum,recnum] = metas.split("\n");
  const newDS = new Dataset({title,url,description,scene,month,freq,sendnum,recnum,content})
  return await newDS.save()
}

const readdir = (path) => new Promise( (resolve, reject) => {
  fs.readdir( path, (err, files) => {resolve(files)} )
})

const readfile = (filename) =>  new Promise( (resolve, reject) => {
  fs.readFile( filename,'utf8',(err, content) => {resolve(content)} )
})

const Allstuff = async () => {
  await Promise.all([Comment, Dataset, User].map(clearCollection))
  console.log("clear database")
  const filenames = await readdir('./data')
  const contents = await Promise.all(filenames.map((f)=>'./data/'+f).map(readfile))
  const datasets = await Promise.all(contents.map(saveDataset))
  const users = await Promise.all([admin, user1, user2, user3, user4].map(saveUser))
  // comment1.author_hashId = users[1].hashId;
  // const comment = await comment1.save();
  // const d = datasets[0];
  // d.comments.push(comment);
  // await d.save();
}
Allstuff().then(()=>{
  console.log("data mock finished")
  mongoose.disconnect()
}).catch(console.log)
